import {messages} from "share/common";
/**
 * Created by tanbingqin on 2018/5/17.
 */
import React from 'react'
import { connect } from 'react-redux'
import {Popover, Row, Col, Card, Avatar, Icon, Badge, Button, Modal, Spin, Input} from 'antd'
import 'styles/setting/sub-application/sub-application.scss'
import noInfo from 'images/no-info.png'
import menuRoute from 'routes/menuRoute'
const { Meta } = Card;
import subApplicationService from 'containers/setting/sub-application/sub-application.service'

class SubApplication extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      subList: [],
      visible: false,
      loading: false,
      appVisible: false,
      sectionName: '',
      newSubApplicationPage: menuRoute.getRouteItem('new-sub-application-privatization', 'key'),   //新建子应用的页面项
      subApplicationDetailPage: menuRoute.getRouteItem('sub-application-detail-privatization', 'key'), //编辑子应用的页面项
      editSubApplication: menuRoute.getRouteItem('edit-sub-application-privatization', 'key'), //编辑子应用的页面项
      EditHomePageCard: menuRoute.getRouteItem('edit-home-page-card-privatization', 'key'), //编辑子应用的页面项
    }
  }

  componentDidMount() {
    this.getAllTenantSubApplicationList();
  }

  //跳转到新建子应用页
  createSubApplication = () => {
    let path = this.state.newSubApplicationPage.url;
    this.context.router.push(path);
  };

  //跳转到子应用详情编辑页
  goSubApplicationDetail = (subApplication) => {
    let path = this.state.subApplicationDetailPage.url.replace(':id', subApplication.id);
    this.context.router.push(path);
  };

  //跳转到编辑子应用详情页
  goEditSubApplication = (e, appCode, sectionCode, appName, appDesc) => {
    this.context.router.push({
      pathname: this.state.editSubApplication.url.replace(":code", appCode),
      state: {
        appCode,
        sectionCode,
        appName,
        appDesc,
      },
    });
  };

  //跳转到编辑子应用详情页
  goEditHomePageCard = (e) => {
    this.context.router.push({
      pathname: this.state.EditHomePageCard.url,
      state: {
      },
    });
  };

  //获取所有单据
  getAllTenantSubApplicationList = () => {
    this.setState({
      loading: true,
    });
    let arr = [];
     subApplicationService.getAllTenantSubApplicationList().then(res => {
      res.data.map(item => {
        if(!item.tenantWidgetDetail){
          item.tenantWidgetDetail = [];
        }
        arr.push(item.sectionCode)
      });
      if(arr.indexOf("THIRD_PARTY") === -1){
        res.data.push({sectionName: '第三方应用', sectionCode: "THIRD_PARTY",tenantWidgetDetail: []})
      }
      this.setState({
        data: res.data,
        loading: false,
      })
    }).catch(err => {
      this.setState({
        loading: false,
      });
    })
  };


  //管理端 获取当前租户下对应section可用列表
  getSectionList = (e, sectionCode, sectionName) => {
    this.setState({
      loading: true,
    });
    this.setState({
      appVisible: true,
      sectionName,
    });
     subApplicationService.getSectionList(sectionCode).then(res => {
      this.setState({
        subList: res.data,
        loading: false,
      })
    }).catch(err => {
      this.setState({
        loading: false,
      });
    })
  };

  render() {
    const { data, visible, appVisible, subList, loading, sectionName } = this.state;
    return (
      <Spin spinning={loading}>
        <div className="sub-application">
        <div style={{fontSize: 14, margin: "20px 0"}}> {messages('setting.key1740')/*以下启用的应用，会出现在App-应用*/}
          <Button type={'primary'} ghost
                  size={'small'}
                  onClick={() => {this.setState({visible: true})}}
                  style={{marginLeft: 10}}>{messages('setting.key1498')/*预览*/}</Button>
        </div>
        {
          data.map((item, index) => {
            return(
                item.sectionCode === "THIRD_PARTY" ?
                  <div key={index}>
                    <Row type="flex"
                         justify="start"
                         align="middle"
                         style={{height: 50, background: '#eee', paddingLeft: 15, marginBottom: 10}}>
                      <Col span={24}>
                        <span style={{fontSize: 16, fontWeight: 700, color: '#656565'}}>
                          {messages('setting.key1039'/*第三方应用*/)}（{item.tenantWidgetDetail.length}）
                        </span>
                      </Col>
                    </Row>
                    <Row gutter={16}>
                      {
                        item.tenantWidgetDetail.map((param, index) =>
                          <Col span={6}
                               style={{marginBottom: 20}}
                               key={index}
                               onClick={() => this.goSubApplicationDetail(param)}>
                            <Card hoverable={true}
                                  style={{borderRadius: 5}}
                                  bodyStyle={{padding: "0 0 0 20px"}}>
                              <Meta
                                avatar = {(
                                  <div>
                                    {param.appIcon && (
                                      <Avatar size="large" src={param.appIcon} />
                                    )}
                                    {!param.appIcon && (
                                      <Avatar size="large" src={noInfo} />
                                    )}
                                  </div>
                                )}
                                description={(
                                  <div>
                                    <span className="card-description">
                                      {param.appName}
                                    </span>
                                    <span style={{fontSize: 12}}>
                                      <Badge status={param.enabled ? 'success' : 'error'}
                                             text={param.enabled ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}/>
                                    </span>
                                  </div>
                                )}
                              />
                            </Card>
                          </Col>
                        )
                      }
                      <Col span={5}
                           style={{marginBottom: 20}}
                           onClick={this.createSubApplication}>
                        <Card hoverable={true}
                              style={{borderRadius: 5, height: 70, borderStyle: 'dashed'}}
                              bodyStyle={{padding: 24}}>
                          <Row type="flex"
                               justify="center"
                               align="middle"
                               className='default-color-font'>
                            <Col span={24}
                                 style={{textAlign: 'center'}}>
                              <Icon type="plus" />
                              <span>&nbsp;{messages('setting.key1040'/*新增应用*/)}</span>
                            </Col>
                          </Row>
                        </Card>
                      </Col>
                    </Row>
                  </div>

                :
                  (
                    <div key={index}>
                      <Row type="flex"
                           justify="start"
                           align="middle"
                           style={{background: '#eee', padding: 10, marginBottom: 20}}>
                        <Col span={24}>
                            <span style={{fontSize: 16, fontWeight: 700, color: '#656565'}}>
                              {item.sectionName}（{item.tenantWidgetDetail.length}）
                            </span>
                          </Col>
                        </Row>
                        <Row gutter={16}>
                          {
                            item.tenantWidgetDetail.map((param, index) =>
                              <Col span={5}
                                   style={{marginBottom: 20}}
                                   key={index}
                                   onClick={(e) => this.goEditSubApplication(e, param.appCode, item.sectionCode, param.appName, param.appDesc)}>
                                <Card hoverable={true}
                                      style={{borderRadius: 5, height: 70}}
                                      bodyStyle={{padding: "0 0 0 20px"}}>
                                  <Meta
                                    avatar = {(
                                      <div>
                                        {param.appIcon && (
                                          <Avatar size="large" src={param.appIcon} />
                                        )}
                                        {!param.appIcon && (
                                          <Avatar size="large" src={noInfo} />
                                        )}
                                      </div>
                                    )}
                                    description={(
                                      <div>
                                        <span className="card-description">
                                          {param.appName}&nbsp;
                                          {
                                            param.appRemark ?
                                            <Popover content={param.appRemark}>
                                              <Icon type="question-circle-o" style={{cursor: "pointer", color: "rgba(0,0,0,0.35)"}}/>
                                            </Popover>
                                              : null
                                          }
                                        </span>
                                        <span style={{fontSize: 12}}>
                                          <Badge status={param.enabled ? 'success' : 'error'}
                                                 text={param.enabled ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}/>
                                        </span>
                                      </div>
                                    )}
                                  />
                                </Card>
                              </Col>
                            )
                          }
                          <Col span={5}
                               style={{marginBottom: 20}}
                               onClick={(e) => {this.getSectionList(e, item.sectionCode, item.sectionName)}}>
                            <Card hoverable={true}
                                  style={{borderRadius: 5, height: 70, borderStyle: 'dashed'}}
                                  bodyStyle={{padding: 24}}>
                              <Row type="flex" justify="center" align="middle" className='default-color-font'>
                                <Col span={24} style={{textAlign: 'center'}}>
                                  <Icon type="plus" />
                                  <span>&nbsp;{messages('setting.key1041'/*从应用列表中选择*/)}</span>
                                </Col>
                              </Row>
                            </Card>
                          </Col>
                        </Row>
                      </div>
                  )
          )
          })
        }
        <Modal onCancel={() => {this.setState({visible: false})}}
               footer={null}
               width={400}
               visible={visible}>
          <div style={{marginTop: 30}}>
            <Row style={{background: '#337ab7'}}>
              <Col span={8}>
                <Icon type="ellipsis" />
                <Icon type="ellipsis" />
                <span style={{fontSize: 9}}>{messages('setting.key1499')/*中国移动*/}</span>
                <Icon type="wifi" />
              </Col>
              <Col span={8} style={{ textAlign: 'center'}}>10：18</Col>
              <Col span={8} style={{ textAlign: 'right', paddingRight: 5}}>
                <Icon type="unlock" /><Icon type="clock-circle-o" />
              </Col>
            </Row>
            <Row style={{background: '#337ab7', color: 'white', padding: '5px 10px'}}>
              <Col span={8}><Icon type="arrow-left" /></Col>
              <Col span={8} style={{textAlign: 'center'}}>{messages('setting.key1500')/*全部应用*/}</Col>
            </Row>
            <Row style={{border: '1px solid rgb(243, 243, 243)', padding: '5px 10px'}}>
              <Col span={16} style={{fontSize: 15}}>{messages('setting.key1501')/*常用功能*/}</Col>
              <Col span={8} style={{textAlign: 'right'}}>
                <a className='default-color-font'>{messages('setting.key1071')/*编辑*/}</a>
              </Col>
            </Row>
            <Row style={{background: 'rgb(243, 243, 243)', height: 10}}><Col span={24}></Col></Row>
            <div style={{maxHeight: 500, overflowY: 'auto'}}>
            {
              data.map((item, index) => {
                return(
                  <div key={index}
                       style={{border: '1px solid rgb(243, 243, 243)', padding: '0 10px'}}>
                    <Row type="flex"
                         justify="start"
                         align="middle"
                         style={{padding: 10}}>
                      <Col span={24}>
                    <span style={{color: '#656565', fontSize: 15}}>
                      {item.sectionName}
                    </span>
                      </Col>
                    </Row>
                    <Row gutter={16}>
                      {
                        item.tenantWidgetDetail.map((item, index) =>
                         item.enabled &&
                          <Col span={6} key={index} style={{marginBottom: 20}}>
                            <Card bodyStyle={{padding: 0, width: 80}}
                                  bordered={false}
                                  cover={<img alt={messages('setting.key1502')/*加载失败*/}
                                              src={item.appIcon ? item.appIcon : noInfo}
                                              style={{height: 60, width: 60}}/>}>
                              <Meta description={<div style={{whiteSpace: 'pre-wrap', fontSize: 13, textAlign: 'left', width: 80}}>{item.appName}</div>}/>
                            </Card>
                          </Col>
                        )
                      }
                    </Row>
                  </div>
                )
              })
            }
            </div>
          </div>
        </Modal>
        <Modal onCancel={() => {this.setState({appVisible: false})}}
               getPopupContainer={() => document.getElementsByClassName('sub-application')[0]}
               footer={null}
               width={620}
               visible={appVisible}
               title={sectionName}>
          { loading ?
            <Spin spinning={loading}/>
            :
          <div>
            <Row gutter={16}>
              {subList.map((param, index) => {
                return (
                  <Col span={12}
                       style={{marginBottom: 20}}
                       key={index}
                       onClick={(e) => this.goEditSubApplication(e, param.appCode, param.source === 'VENDOR' ? 'VENDOR' : null , param.appName, param.appDesc, param)}>
                    <Card hoverable={true}
                          style={{borderRadius: 5, height: 70}}
                          bodyStyle={{padding: 18}}>
                      <Meta
                        avatar = {(
                          <div>
                            {param.appIcon && (
                              <Avatar size="large"
                                      src={param.appIcon}
                                      style={{background: 'none'}}/>
                            )}
                            {!param.appIcon && (
                              <Avatar size="large"
                                      src={noInfo}
                                      style={{background: 'none'}}/>
                            )}
                          </div>
                        )}
                        description={(
                          <div>
                            <div className="card-description">
                              {param.appName}&nbsp;
                              {
                                param.appRemark ?
                                  <Popover content={param.appRemark}>
                                    <Icon type="question-circle-o" style={{cursor: "pointer", color: "rgba(0,0,0,0.35)"}}/>
                                  </Popover>
                                  : null
                              }
                            </div>
                            {
                              param.tenantWidget ?
                                (param.tenantWidget.enabled === null ? null :
                                  <span style={{fontSize: 12}}>
                                    <Badge status={param.tenantWidget.enabled ? 'success' : 'error'}
                                           text={param.tenantWidget.enabled ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}/>
                                  </span>
                                )
                                : null
                            }
                          </div>
                        )}
                      />
                    </Card>
                  </Col>
                )
              })
              }
            </Row>
          </div>
          }
        </Modal>
      </div>
      </Spin>
    )
  }
}

SubApplication.contextTypes ={
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language
  }
}

export default connect(mapStateToProps)(SubApplication)
